Skip to content

gh-162738: Preserve exception context when exit callbacks re-raise - #162810

Open
subotac wants to merge 1 commit into
python:mainfrom
subotac:fix/exitstack-exception-context-cycle
Open

subotac wants to merge 1 commit into
python:mainfrom
subotac:fix/exitstack-exception-context-cycle

Conversation

@subotac

@subotac subotac commented Nov 28, 2026 •

Copy link
Copy Markdown

Fixes #162738

Preserve the existing __context__ when an exit callback re-raises the pending exception. This prevents ExitStack and AsyncExitStack from setting the exception as its own contexт

The regression test checks that both stacks preserve the original exception from the with body as the context of the cleanup exception

Comment thread Lib/contextlib.py
frame_exc = sys.exception()
def _fix_exception_context(new_exc, old_exc):
if new_exc is old_exc:
# Re-raising the pending exception preserves its context.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This comment doesn't seem to be relevant.

@picnixz picnixz added the AI-needs-explanation AI-assisted work that needs further explanation and follow up from the contributor label Nov 28, 2026
@bedevere-app

bedevere-app Bot commented Nov 28, 2026

Copy link
Copy Markdown

Thank you for your interest in contributing to Python. This is a community-driven project, and we want it to be a welcoming place to learn and collaborate.

Contributors are responsible for reviewing and understanding what they submit, checking its claims, and being able to explain changes in their own words. This helps reviewers focus on the contribution and leaves more time to support other contributors.

This contribution appears to have been authored with AI assistance. Please explain your contribution in your own words and describe how you checked its correctness.

Please read our guidelines for using AI tools.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

AI-needs-explanation AI-assisted work that needs further explanation and follow up from the contributor awaiting review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Self-referential exception.__context__

2 participants